package _mst;

import java.util.ArrayList;
import java.util.List;

/**
 * 面试题 08.12. 八皇后
 */
public class T0812 {
    private List<List<String>> ans;
    private List<Integer> path;
    private int n;

    public List<List<String>> solveNQueens(int n) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.n = n;
        dfs(0);
        return ans;
    }

    private void dfs(int i) {
        if (path.size() == n) {
            List<String> list = new ArrayList<>();
            for (Integer integer : path) {
                StringBuilder sb = new StringBuilder();
                for (int index = 0; index < n; index++) {
                    sb.append(index == integer ? "Q" : ".");
                }
                list.add(sb.toString());
            }
            ans.add(list);
            return;
        }
        for (int j = 0; j < n; j++) {
            if (!judge(i, j)) continue;
            path.add(i, j);
            dfs(i + 1);
            path.remove(path.size() - 1);
        }
    }

    private boolean judge(int i, int j) {
        for (int row = 0; row < path.size(); row++) {
            Integer column = path.get(row);
            if (row == i || column == j || (i + j) == (row + column) || (i - row) == (j - column)) return false;
        }
        return true;
    }
}
